#include "Logger.hpp" // 修正：直接包含大写的 Logger.hpp
#include <iostream>
#include <chrono>
#include <vector>
#include <numeric>   // For std::accumulate
#include <algorithm> // For std::sort
#include <iomanip>   // For std::fixed and std::setprecision

// 定义要写入的日志数量
const int LOG_COUNT = 100000; // 延迟测试不需要太多次，10万次足矣

// 一个辅助函数，用于将纳秒转换为更易读的格式
void print_nanoseconds(long long ns) {
    if (ns < 1000) {
        std::cout << ns << " ns";
    } else if (ns < 1000000) {
        std::cout << std::fixed << std::setprecision(2) << ns / 1000.0 << " us"; // 微秒
    } else {
        std::cout << std::fixed << std::setprecision(2) << ns / 1000000.0 << " ms"; // 毫秒
    }
}

void run_latency_benchmark(senlog::Logger::ptr logger, const std::string& logger_type) {
    std::cout << "--- Starting Latency Benchmark for: " << logger_type << " ---" << std::endl;
    
    // 创建一个 vector 来存储每一次调用的延迟（单位：纳秒）
    std::vector<long long> latencies;
    latencies.reserve(LOG_COUNT);

    // --- 测量循环 ---
    for (int i = 0; i < LOG_COUNT; ++i) {
        auto start = std::chrono::high_resolution_clock::now();
        
        LOG_INFO(logger, "This is latency test message %d", i);
        
        auto end = std::chrono::high_resolution_clock::now();
        auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start);
        latencies.push_back(duration.count());
    }

    // --- 数据分析 ---
    // 1. 对所有延迟数据进行排序，以便计算百分位数
    std::sort(latencies.begin(), latencies.end());

    // 2. 计算总耗时和平均延迟
    long long total_duration_ns = std::accumulate(latencies.begin(), latencies.end(), 0LL);
    
    std::cout << "Total producer time: ";
    print_nanoseconds(total_duration_ns);
    std::cout << std::endl;

    std::cout << "Average latency:     ";
    print_nanoseconds(total_duration_ns / LOG_COUNT);
    std::cout << std::endl;

    // 3. 计算百分位延迟 (P50, P99, P99.9) 和最大延迟
    std::cout << "Median latency (P50):  ";
    print_nanoseconds(latencies[latencies.size() * 0.50]);
    std::cout << std::endl;

    std::cout << "99th percentile (P99): ";
    print_nanoseconds(latencies[latencies.size() * 0.99]);
    std::cout << std::endl;

    std::cout << "99.9th percentile (P99.9): ";
    print_nanoseconds(latencies[latencies.size() * 0.999]);
    std::cout << std::endl;

    std::cout << "Maximum latency:     ";
    print_nanoseconds(latencies.back());
    std::cout << std::endl;

    std::cout << "--------------------------------------------------------" << std::endl << std::endl;

    // 异步模式需要等待后台线程完成工作，以免影响下一个测试
    if (logger_type.find("Async") != std::string::npos) {
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }
}

int main() {
    // 1. 同步日志器延迟测试
    senlog::LocalLoggerBuilder sync_builder;
    sync_builder.buildLoggerName("sync_logger")
                .buildLoggerType(senlog::LoggerType::SYNC_LOGGER)
                .addSink<senlog::FileLogSink>("./logs/sync_latency.log");
    auto sync_logger = sync_builder.build();
    run_latency_benchmark(sync_logger, "Sync Logger");

    // 2. 异步安全模式日志器延迟测试
    senlog::LocalLoggerBuilder async_safe_builder;
    async_safe_builder.buildLoggerName("async_safe_logger")
                     .buildLoggerType(senlog::LoggerType::ASYNC_LOGGER)
                     .addSink<senlog::FileLogSink>("./logs/async_safe_latency.log");
    auto async_safe_logger = async_safe_builder.build();
    run_latency_benchmark(async_safe_logger, "Async Logger (Safe Mode)");

    // 3. 异步不安全模式日志器延迟测试
    senlog::LocalLoggerBuilder async_unsafe_builder;
    async_unsafe_builder.buildLoggerName("async_unsafe_logger")
                        .buildLoggerType(senlog::LoggerType::ASYNC_LOGGER)
                        .buildEnableUnsafe()
                        .addSink<senlog::FileLogSink>("./logs/async_unsafe_latency.log");
    auto async_unsafe_logger = async_unsafe_builder.build();
    run_latency_benchmark(async_unsafe_logger, "Async Logger (Unsafe Mode)");

    return 0;
}